<?php
namespace app\index\worker;

use app\index\model\WorkerModel;
use think\worker\Server;
use Workerman\Lib\Timer;

class Worker extends Server
{
    protected $host = '0.0.0.0';
    protected $port = 3342;
    protected $heartTime = 30;
    protected $option = [
        'count'=> 1,
        'name'=> 'think'
    ];
    protected $uidConnections = [];

    public function onMessage($connection, $data)
    {

        try {
            $wsData = json_decode($data,true);
        } catch (\Exception $e) {
            $wsData = [];
        }

        $connection->lastMessageTime = time();
        if(!isset($connection->uid) || $connection->uid < 1){
            $uid = isset($wsData['uid']) ? $wsData['uid'] : 0;
            $type = isset($wsData['type']) ? $wsData['type'] : '';
            if($uid > 0 && in_array($type, ['mob','pc'])){
                $connection->uid = $uid;
                $connection->type = $type;
                $this->uidConnections[$connection->type.$connection->uid] = $connection;
            }
        }

//
//        dump(count($this->uidConnections));
//        foreach ($this->uidConnections as $key => $value) {
//            dump($this->uidConnections[$key]->uid);
//            dump($this->uidConnections[$key]->type);
//            dump($this->uidConnections[$key]->lastMessageTime);
//            dump('xxxxxxxxxxxxxxxxxxxxxxxxxx');
//        }

        return;
    }

    public function onWorkerStart($worker)
    {
        Timer::add(2, function()use($worker){
            $time_now = time();
            foreach($this->uidConnections as $connection) {
                if (empty($connection->lastMessageTime)) {
                    $connection->lastMessageTime = $time_now;
                    continue;
                }
                if ($time_now - $connection->lastMessageTime > $this->heartTime) {
                    $connection->close();
                    unset($this->uidConnections[$connection->type.$connection->uid]);
                }
            }
        });




        Timer::add(5, function()use($worker){
            $data = WorkerModel::select()->toArray();
            foreach ($data as $item){
                if(isset($this->uidConnections['pc'.$item['uid']])){
                    $conn = $this->uidConnections['pc'.$item['uid']];
                    $conn->send(json_encode($item));
                    WorkerModel::where(['id'=>$item['id']])->delete();
                }
                if(isset($this->uidConnections['mob'.$item['uid']])){
                    $conn = $this->uidConnections['mob'.$item['uid']];
                    $conn->send(json_encode($item));
                    WorkerModel::where(['id'=>$item['id']])->delete();
                }
            }
        });
    }





}